<template>
	<view class="container">
		<!-- 添加用户按钮 -->
		<view class="header">
			<view class="title">用户管理</view>
			<button class="add-btn" @click="addUser">添加用户</button>
		</view>
		
		<!-- 用户列表 -->
		<view class="user-list">
			<view class="list-header">
				<text class="header-item">用户名</text>
				<text class="header-item">昵称</text>
				<text class="header-item">角色</text>
				<text class="header-item">状态</text>
				<text class="header-item">操作</text>
			</view>
			
			<view v-if="loading" class="loading">
				<text>加载中...</text>
			</view>
			
			<view v-else-if="userList.length === 0" class="empty">
				<text>暂无用户数据</text>
			</view>
			
			<view v-else>
				<view v-for="user in userList" :key="user._id" class="user-item">
					<text class="item-text">{{ user.username }}</text>
					<text class="item-text">{{ user.nickname || '-' }}</text>
					<text class="item-text role" :class="user.role">{{ user.role === 'admin' ? '管理员' : '普通用户' }}</text>
					<text class="item-text status" :class="user.status">{{ user.status === 'active' ? '正常' : '禁用' }}</text>
					<view class="user-actions">
						<button class="edit-btn" @click="editUser(user)">编辑</button>
						<button class="delete-btn" @click="deleteUser(user._id)">删除</button>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 分页 -->
		<view class="pagination" v-if="total > pageSize">
			<button class="page-btn" :disabled="currentPage <= 1" @click="changePage(currentPage - 1)">上一页</button>
			<text class="page-info">{{ currentPage }}/{{ Math.ceil(total / pageSize) }}</text>
			<button class="page-btn" :disabled="currentPage >= Math.ceil(total / pageSize)" @click="changePage(currentPage + 1)">下一页</button>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			userList: [],
			loading: false,
			currentPage: 1,
			pageSize: 10,
			total: 0
		}
	},
	onLoad() {
		this.checkPermission();
	},
	
	onShow() {
		// 页面显示时重新加载用户列表（从编辑页面返回时刷新数据）
		if (this.userList.length > 0) {
			this.loadUserList();
		}
	},
	
	methods: {
		// 权限检查
		checkPermission() {
			const userInfo = uni.getStorageSync('userInfo');
			if (!userInfo || userInfo.role !== 'admin') {
				uni.showModal({
					title: '权限不足',
					content: '只有管理员才能访问用户管理页面',
					showCancel: false,
					success: () => {
						uni.switchTab({
							url: '/pages/index/index'
						});
					}
				});
				return;
			}
			// 如果是管理员，加载用户列表
			this.loadUserList();
		},
		
		// 加载用户列表
		async loadUserList() {
			this.loading = true;
			try {
				const res = await uniCloud.callFunction({
					name: 'userManage',
					data: {
						action: 'list',
						page: this.currentPage,
						limit: this.pageSize
					}
				});
				
				if (res.result.code === 0) {
					this.userList = res.result.data.list;
					this.total = res.result.data.total;
				} else {
					uni.showToast({
						title: res.result.message,
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('加载用户列表失败:', error);
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				});
			} finally {
				this.loading = false;
			}
		},
		
		// 添加用户
		addUser() {
			uni.navigateTo({
				url: '/pages/userEdit/userEdit'
			});
		},
		
		// 编辑用户
		editUser(user) {
			const params = {
				id: user._id,
				username: user.username,
				nickname: user.nickname || '',
				email: user.email || '',
				mobile: user.mobile || '',
				role: user.role,
				status: user.status
			};
			
			const queryString = Object.keys(params)
				.map(key => `${key}=${encodeURIComponent(params[key])}`)
				.join('&');
			
			uni.navigateTo({
				url: `/pages/userEdit/userEdit?${queryString}`
			});
		},
		
		// 删除用户
		deleteUser(userId) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个用户吗？此操作不可恢复。',
				success: async (res) => {
					if (res.confirm) {
						try {
							const result = await uniCloud.callFunction({
								name: 'userManage',
								data: {
									action: 'delete',
									userId: userId
								}
							});
							
							if (result.result.code === 0) {
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
								this.loadUserList();
							} else {
								uni.showToast({
									title: result.result.message,
									icon: 'none'
								});
							}
						} catch (error) {
							console.error('删除用户失败:', error);
							uni.showToast({
								title: '删除失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		
		// 分页切换
		changePage(page) {
			if (page < 1 || page > Math.ceil(this.total / this.pageSize)) {
				return;
			}
			this.currentPage = page;
			this.loadUserList();
		}
	}
}
</script>

<style scoped>
.container {
	padding: 20rpx;
	background-color: #f8f9fa;
	min-height: 100vh;
}

/* 头部样式 */
.header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	border-radius: 20rpx;
	margin-bottom: 30rpx;
	box-shadow: 0 8rpx 25rpx rgba(102, 126, 234, 0.3);
}

.title {
	font-size: 36rpx;
	font-weight: bold;
	color: white;
}

.add-btn {
	background: rgba(255, 255, 255, 0.2);
	color: white;
	border: 2rpx solid rgba(255, 255, 255, 0.3);
	border-radius: 50rpx;
	padding: 16rpx 32rpx;
	font-size: 28rpx;
	font-weight: 500;
	transition: all 0.3s ease;
}

.add-btn:active {
	background: rgba(255, 255, 255, 0.3);
	transform: scale(0.95);
}

/* 用户列表样式 */
.user-list {
	background: white;
	border-radius: 20rpx;
	overflow: hidden;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.list-header {
	display: flex;
	background: #f8f9fa;
	padding: 24rpx 20rpx;
	border-bottom: 2rpx solid #eee;
}

.header-item {
	flex: 1;
	font-size: 28rpx;
	font-weight: bold;
	color: #666;
	text-align: center;
}

.user-item {
	display: flex;
	align-items: center;
	padding: 30rpx 20rpx;
	border-bottom: 1rpx solid #f0f0f0;
	transition: background-color 0.3s ease;
}

.user-item:last-child {
	border-bottom: none;
}

.user-item:active {
	background-color: #f8f9fa;
}

.item-text {
	flex: 1;
	font-size: 28rpx;
	color: #333;
	text-align: center;
	line-height: 1.4;
}

.item-text.role.admin {
	color: #e74c3c;
	font-weight: bold;
}

.item-text.role.user {
	color: #3498db;
}

.item-text.status.active {
	color: #27ae60;
	font-weight: 500;
}

.item-text.status.disabled {
	color: #95a5a6;
}

.user-actions {
	flex: 1;
	display: flex;
	justify-content: center;
	gap: 16rpx;
}

.edit-btn, .delete-btn {
	padding: 12rpx 24rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	font-weight: 500;
	border: none;
	transition: all 0.3s ease;
}

.edit-btn {
	background: #3498db;
	color: white;
}

.edit-btn:active {
	background: #2980b9;
	transform: scale(0.95);
}

.delete-btn {
	background: #e74c3c;
	color: white;
}

.delete-btn:active {
	background: #c0392b;
	transform: scale(0.95);
}

/* 加载和空状态 */
.loading, .empty {
	padding: 80rpx 20rpx;
	text-align: center;
	color: #999;
	font-size: 28rpx;
}

/* 分页样式 */
.pagination {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 40rpx 20rpx;
	background: white;
	border-radius: 20rpx;
	margin-top: 30rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
	gap: 30rpx;
}

.page-btn {
	padding: 16rpx 32rpx;
	border-radius: 25rpx;
	font-size: 28rpx;
	font-weight: 500;
	border: 2rpx solid #667eea;
	color: #667eea;
	background: white;
	transition: all 0.3s ease;
}

.page-btn:not(:disabled):active {
	background: #667eea;
	color: white;
	transform: scale(0.95);
}

.page-btn:disabled {
	border-color: #ddd;
	color: #999;
	background: #f5f5f5;
}

.page-info {
	font-size: 28rpx;
	color: #666;
	font-weight: 500;
}
</style>